<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item :label="t('imrStudent.index.search.keyword')" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          :placeholder="
            t('common.inputTextPlaceholder') + t('imrStudent.index.search.keywordPlaceholder')
          "
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          :disabled="advancedSearching"
        />
      </el-form-item>
      <el-form-item :label="t('imrStudent.fields.grade')" prop="grade">
        <el-select
          v-model="queryParams.grade"
          :placeholder="t('common.selectTextPlaceholder') + t('imrStudent.fields.grade')"
          clearable
          class="!w-240px"
          @change="handleQuery"
          :disabled="advancedSearching"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.IMR_INFO_GRADE).reverse()"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('imrStudent.fields.trainingLevel')" prop="trainingLevel">
        <el-select
          v-model="queryParams.trainingLevel"
          :placeholder="t('common.selectTextPlaceholder') + t('imrStudent.fields.trainingLevel')"
          clearable
          class="!w-240px"
          @change="handleQuery"
          :disabled="advancedSearching"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.IMR_INFO_TRAINING_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('imrStudent.fields.classroom')" prop="classroom">
        <el-select
          v-model="queryParams.classroom"
          :placeholder="t('common.selectTextPlaceholder') + t('imrStudent.fields.classroom')"
          clearable
          class="!w-240px"
          @change="handleQuery"
          :disabled="advancedSearching"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.IMR_INFO_CLASSROOM).reverse()"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('imrStudent.fields.studentStatus')" prop="studentStatus">
        <el-select
          v-model="queryParams.studentStatus"
          :placeholder="t('common.selectTextPlaceholder') + t('imrStudent.fields.studentStatus')"
          clearable
          class="!w-240px"
          @change="handleQuery"
          :disabled="advancedSearching"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.IMR_INFO_STUDENT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('imrStudent.fields.studentType')" prop="studentType">
        <el-select
          v-model="queryParams.studentType"
          :placeholder="t('common.selectTextPlaceholder') + t('imrStudent.fields.studentType')"
          clearable
          class="!w-240px"
          @change="handleQuery"
          :disabled="advancedSearching"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.IMR_INFO_STUDENT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('imrStudent.fields.primaryMentor')" prop="primaryMentor">
        <el-input
          v-model="queryParams.primaryMentor"
          :placeholder="t('common.inputTextPlaceholder') + t('imrStudent.fields.primaryMentor')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          :disabled="advancedSearching"
        />
      </el-form-item>
      <el-form-item :label="t('imrStudent.fields.inschoolFlag')" prop="inschoolFlag">
        <el-select
          v-model="queryParams.inschoolFlag"
          :placeholder="t('common.selectTextPlaceholder') + t('imrStudent.fields.inschoolFlag')"
          clearable
          class="!w-240px"
          @change="handleQuery"
          :disabled="advancedSearching"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.IMR_INFO_INSCHOOL_FLAG)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('imrStudent.fields.originalCollege')" prop="originalCollege">
        <el-input
          v-model="queryParams.originalCollege"
          :placeholder="t('common.inputTextPlaceholder') + t('imrStudent.fields.originalCollege')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          :disabled="advancedSearching"
        />
      </el-form-item>
      <el-form-item :label="t('imrStudent.fields.arpNumber')" prop="arpNumber">
        <el-input
          v-model="queryParams.arpNumber"
          :placeholder="t('common.inputTextPlaceholder') + t('imrStudent.fields.arpNumber')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          :disabled="advancedSearching"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" :disabled="advancedSearching">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.search') }}
        </el-button>
        <el-button @click="resetQuery" :disabled="advancedSearching">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
        <el-button
          type="primary"
          plain
          @click="showStudentInfo(null, 'create')"
          v-hasPermi="['core:imr-student:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('action.add') }}
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleImport"
          v-hasPermi="['core:imr-student:export']"
        >
          <Icon icon="ep:upload" class="mr-5px" />
          {{ t('action.import') }}
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handlePhotoImport"
          v-hasPermi="['core:imr-student:export']"
        >
          <Icon icon="ep:upload" class="mr-5px" />
          {{ t('photoImport.title') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['core:imr-student:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          {{ t('action.export') }}
        </el-button>
        <ConditionTree
          id="imrstudent-condition-tree"
          :schemata="imrStudentSchema"
          @search="handleAdvanceSearch"
        />
        <SendChat />
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <vxe-toolbar ref="toolbarRef" custom />
    <vxe-table
      id="iImrStudent-table"
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :custom-config="vxeTableConfig"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('imrStudent.fields.studentPhoto')"
        field="studentPhoto"
        align="center"
        min-width="100"
      >
        <template #default="scope">
          <el-image
            class="student-avatar"
            :src="scope.row.studentPhoto"
            :preview-src-list="[scope.row.studentPhoto]"
            fit="cover"
          >
            <template #error>
              <div class="image-slot">
                {{ t('ustcstudent.view.noPhoto') }}
              </div>
            </template>
          </el-image>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('imrStudent.fields.studentCode')"
        field="studentCode"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudent.fields.studentName')"
        field="studentName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudent.fields.gender')"
        field="gender"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudent.fields.grade')"
        field="grade"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('imrStudent.fields.inschoolFlag')"
        field="inschoolFlag"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudent.fields.studentStatus')"
        field="studentStatus"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('imrStudent.fields.leaveDate')"
        field="leaveDate"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :formatter="vxeDateFormatter2"
        :visible="false"
      />
      <vxe-column
        :title="t('imrStudent.fields.studentType')"
        field="studentType"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudent.fields.classroom')"
        field="classroom"
        align="center"
        show-header-overflow
        show-overflow
        min-width="120"
      />
      <vxe-column
        :title="t('imrStudent.fields.personalPhone1')"
        field="personalPhone1"
        align="center"
        show-header-overflow
        show-overflow
        min-width="120"
      />
      <vxe-column
        :title="t('imrStudent.fields.personalEmail1')"
        field="personalEmail1"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('imrStudent.fields.identityNumber')"
        field="identityNumber"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('imrStudent.fields.trainingLevel')"
        field="trainingLevel"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('imrStudent.fields.primaryMentorCode')"
        field="primaryMentorCode"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('imrStudent.fields.primaryMentor')"
        field="primaryMentor"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudent.fields.researchDept')"
        field="researchDept"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudent.fields.originalCollege')"
        field="originalCollege"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudent.fields.birthdate')"
        field="birthdate"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :formatter="vxeDateFormatter2"
        :visible="false"
      />
      <vxe-column
        :title="t('imrStudent.fields.ethnic')"
        field="ethnic"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('imrStudent.fields.politicalStatus')"
        field="politicalStatus"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('imrStudent.fields.homeAddress')"
        field="homeAddress"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('imrStudent.fields.homeTelephone')"
        field="homeTelephone"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('imrStudent.fields.arpNumber')"
        field="arpNumber"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudent.fields.createTime')"
        field="createTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :formatter="vxeDateFormatter"
        :visible="false"
      />
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="80"
      >
        <template #default="scope">
          <el-button link type="primary" @click="showStudentInfo(scope.row.id, 'view')">
            {{ t('action.detail') }}
          </el-button>
          <!--          <el-button-->
          <!--            link-->
          <!--            type="primary"-->
          <!--            @click="openForm('update', scope.row.id)"-->
          <!--            v-hasPermi="['core:imr-student:update']"-->
          <!--          >-->
          <!--            {{ t('action.edit') }}-->
          <!--          </el-button>-->
          <!--          <el-button-->
          <!--            link-->
          <!--            type="danger"-->
          <!--            @click="handleDelete(scope.row.id)"-->
          <!--            v-hasPermi="['core:imr-student:delete']"-->
          <!--          >-->
          <!--            {{ t('action.delete') }}-->
          <!--          </el-button>-->
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ImrStudentForm ref="formRef" @success="getList" />
  <ImrStudentView ref="studentViewRef" @refresh="getList" />
  <ExcelImportForm
    ref="importFormRef"
    object-name="联培学生信息"
    upload-url="/core/imr-student/import"
    template-url="/core/imr-student/get-import-template"
    @success="getList"
  />
  <ImrPhotoImportForm ref="photoImportRef" upload-url="/core/imr-student/import-photo" />
</template>

<script setup lang="ts">
import { vxeDateFormatter, vxeDateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { ImrStudentApi, ImrStudentVO } from '@/api/core/imrstudent'
import ImrStudentForm from './ImrStudentForm.vue'
import ImrStudentView from './components/ImrStudentView.vue'
import ExcelImportForm from '@/components/ExcelImportForm/index.vue'
import type { VxeTablePropTypes, VxeToolbarInstance, VxeTableInstance } from 'vxe-table'
import { imrStudentSchema } from '@/views/core/imrstudent/schema'
import { useAppStore } from '@/store/modules/app'
import SendChat from '@/components/SendChat/index.vue'
import ImrPhotoImportForm from './components/ImrPhotoImportForm.vue'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

/** 联培学生信息 列表 */
defineOptions({ name: 'ImrStudent' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const toolbarRef = ref<VxeToolbarInstance>()
const tableRef = ref<VxeTableInstance>()

const loading = ref(true) // 列表的加载中
const list = ref<ImrStudentVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const advancedSearching = ref(false) // 高级搜索
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  keyword: undefined,
  advanced: undefined,
  accountId: undefined,
  studentPhoto: undefined,
  studentCode: undefined,
  studentName: undefined,
  grade: undefined,
  classroom: undefined,
  studentType: undefined,
  inschoolFlag: undefined,
  identityNumber: undefined,
  trainingLevel: undefined,
  primaryMentorId: undefined,
  primaryMentorCode: undefined,
  primaryMentor: undefined,
  researchDeptId: undefined,
  researchDept: undefined,
  originalCollege: undefined,
  gender: undefined,
  birthdate: [],
  ethnic: undefined,
  politicalStatus: undefined,
  homeAddress: undefined,
  homeTelephone: undefined,
  personalPhone1: undefined,
  personalEmail1: undefined,
  arpNumber: undefined,
  studentStatus: undefined,
  leaveDate: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const studentViewRef = ref<InstanceType<typeof ImrStudentView>>()

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ImrStudentApi.getImrStudentPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  advancedSearching.value = false
  ;(queryParams as any).advanced = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref<InstanceType<typeof ImrStudentForm>>()
const openForm = (type: string, id?: number) => {
  formRef.value?.open(type, id)
}

/** 导入 */
const importFormRef = ref<InstanceType<typeof ExcelImportForm>>()
const handleImport = () => {
  importFormRef.value?.open()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ImrStudentApi.deleteImrStudent(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ImrStudentApi.exportImrStudent(queryParams)
    download.excel(data, '联培学生信息.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleAdvanceSearch = (base64Advanced?: string) => {
  ;(queryParams as any).advanced = base64Advanced
  advancedSearching.value = !!base64Advanced
  handleQuery()
}

const showStudentInfo = (id: number | null, mode: string) => {
  studentViewRef.value?.open(id, mode)
}

const photoImportRef = ref<InstanceType<typeof ImrPhotoImportForm>>()
const handlePhotoImport = () => {
  photoImportRef.value?.open()
}

/** 初始化 **/
onMounted(() => {
  getList()

  const table = tableRef.value
  const toolbar = toolbarRef.value
  if (table && toolbar) {
    table.connect(toolbar)
  }
})
</script>

<style lang="scss" scoped>
.student-avatar {
  width: 80px;
  height: 80px;
  display: block;
  margin: 5px auto;
  border-radius: 6px;

  :deep(.image-slot) {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 14px;
  }
}
</style>
